<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <img 
              v-if="userInfo.avatar" 
              :src="userInfo.avatar" 
              :alt="userInfo.username" 
              class="avatar-img"
              @error="handleAvatarError"
            />
            <div v-else class="avatar-placeholder">
              <el-icon><User /></el-icon>
            </div>
          </div>
          <el-button type="primary" size="small" @click="showAvatarDialog">
            更换头像
          </el-button>
        </div>
        
        <div class="user-info-section">
          <!-- 添加调试信息 -->
          <h2>{{ userInfo.username }}</h2>
          <p class="user-type">
            <el-tag :type="userInfo.user_type === 'admin' ? 'danger' : 'success'">
              {{ userInfo.user_type === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </p>
          <p class="user-status">
            <el-tag :type="userInfo.is_active ? 'success' : 'danger'">
              {{ userInfo.is_active ? '启用' : '禁用' }}
            </el-tag>
          </p>
        </div>
      </div>
      
      <el-divider />
      
      <div class="profile-details">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="用户ID">
                {{ userInfo.id }}
              </el-descriptions-item>
              <el-descriptions-item label="用户名">
                {{ userInfo.username }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                {{ userInfo.phone_number }}
              </el-descriptions-item>
              <el-descriptions-item label="注册时间">
                {{ formatDateTime(userInfo.created_at) }}
              </el-descriptions-item>
              <el-descriptions-item label="最后登录">
                {{ userInfo.last_login ? formatDateTime(userInfo.last_login) : '从未登录' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          
          <el-col :span="12">
            <el-form
              ref="profileFormRef"
              :model="profileForm"
              :rules="profileRules"
              label-width="80px"
              class="profile-form"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="profileForm.username" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone_number">
                <el-input v-model="profileForm.phone_number" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileForm.email" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updateProfile">保存信息</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      :before-close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="old_password">
          <el-input 
            v-model="passwordForm.old_password" 
            type="password" 
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input 
            v-model="passwordForm.new_password" 
            type="password" 
            show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirm_password">
          <el-input 
            v-model="passwordForm.confirm_password" 
            type="password" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="上传头像"
      width="500px"
      :before-close="handleAvatarDialogClose"
    >
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          action="/api/health/upload/image/"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
        >
          <img 
            v-if="avatarPreview" 
            :src="avatarPreview" 
            class="avatar-preview"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <p class="upload-tip">点击上传头像，支持JPG/PNG格式，大小不超过2MB</p>
      </div>
      <template #footer>
        <el-button @click="avatarDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAvatar">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api/user'
import type { UserInfo } from '@/types/user'
import { formatDateTime } from '@/utils'

const userStore = useUserStore()

// 表单引用
const profileFormRef = ref()
const passwordFormRef = ref()

// 对话框状态
const passwordDialogVisible = ref(false)
const avatarDialogVisible = ref(false)

// 头像预览
const avatarPreview = ref('')

// 用户信息
const userInfo = reactive<UserInfo>({
  id: 0,
  username: '',
  email: '',
  phone_number: '',
  user_type: 'user',
  is_active: true,
  date_joined: '',
  last_login: '',
  avatar: ''
})

// 表单数据
const profileForm = reactive({
  username: '',
  phone_number: '',
  email: ''
})

const passwordForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

// 表单验证规则
const profileRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone_number: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules = {
  old_password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirm_password: [
    { 
      validator: (value: string, callback: any) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理头像加载错误
const handleAvatarError = () => {
  userInfo.avatar = ''
}

// 显示头像对话框
const showAvatarDialog = () => {
  avatarDialogVisible.value = true
}

// 头像上传前检查
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  
  // 设置预览
  if (isJPG && isLt2M) {
    avatarPreview.value = URL.createObjectURL(file)
  }
  
  return isJPG && isLt2M
}

// 头像上传成功
const handleAvatarSuccess = (response: any, file: File) => {
  // 使用API返回的URL而不是本地预览
  if (response && response.url) {
    avatarPreview.value = response.url
  } else {
    avatarPreview.value = URL.createObjectURL(file)
  }
}

// 头像上传失败处理函数已移除

// 更新头像
const updateAvatar = async () => {
  if (!avatarPreview.value) {
    ElMessage.warning('请先选择头像图片')
    return
  }
  
  try {
    // 调用API更新头像
    await userApi.updateAvatar(avatarPreview.value)
    
    // 更新用户存储中的信息
    if (userStore.userInfo) {
      userStore.userInfo.avatar = avatarPreview.value
    }
    
    // 更新本地用户信息
    userInfo.avatar = avatarPreview.value
    
    avatarDialogVisible.value = false
    ElMessage.success('头像更新成功')
  } catch (error) {
    ElMessage.error('头像更新失败')
  }
}

// 关闭头像对话框
const handleAvatarDialogClose = () => {
  avatarDialogVisible.value = false
  avatarPreview.value = ''
}

// 关闭密码对话框
const handlePasswordDialogClose = () => {
  passwordDialogVisible.value = false
  passwordFormRef.value?.resetFields()
}

// 更新个人信息
const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    const valid = await profileFormRef.value.validate()
    if (!valid) return
    
    // 调用API更新用户信息
    await userApi.updateProfile({
      username: profileForm.username,
      phone_number: profileForm.phone_number,
      email: profileForm.email
    })
    
    // 更新用户存储中的信息
    if (userStore.userInfo) {
      userStore.userInfo.username = profileForm.username
      userStore.userInfo.phone_number = profileForm.phone_number
      userStore.userInfo.email = profileForm.email
    }
    
    ElMessage.success('个人信息更新成功')
  } catch (error: any) {
    ElMessage.error(error.message || '更新失败')
  }
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    // 这里应该调用实际的修改密码API
    // 暂时使用模拟逻辑
    ElMessage.success('密码修改成功，请重新登录')
    passwordDialogVisible.value = false
    passwordFormRef.value?.resetFields()
  } catch (error: any) {
    ElMessage.error(error.message || '密码修改失败')
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await userApi.getProfile()
    // 确保正确更新所有字段
    Object.assign(userInfo, response)
    Object.assign(profileForm, {
      username: response?.username || '',
      phone_number: response?.phone_number || '',
      email: response?.email || ''
    })
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 1200px;
  margin: 0 auto;
}

.profile-header {
  display: flex;
  align-items: center;
  padding: 20px 0;
}

.avatar-section {
  text-align: center;
  margin-right: 40px;
}

.avatar-wrapper {
  position: relative;
  width: 120px;
  height: 120px;
  margin: 0 auto 15px;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #ebeef5;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #ebeef5;
}

.avatar-placeholder .el-icon {
  font-size: 40px;
  color: #909399;
}

.user-info-section h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.user-type, .user-status {
  margin: 5px 0;
}

.profile-details {
  padding: 20px 0;
}

.profile-form {
  margin-top: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}
</style>